<template>
    <div class="articleDetail">
·
        <div v-if='articleDetail != null  '>

            <div>
                <el-row :gutter="20">
                    <!--                    文章主内容-->
                    <el-col :span="18">
                        <div class="articleMain">

                            <!--                        文章标题-->
                            <div class="title"><h2>{{articleDetail.title}}</h2></div>

                            <div class="title"><h4>{{articleDetail.summary}}</h4></div>

                            <el-divider>开始阅读</el-divider>

                            <!--                        文章内容-->
                            <div class="markdown">
                                <MarkdownPro
                                        :isPreview="true"
                                        :autoSave="true"
                                        :value='articleDetail.content'
                                        :initialValue='articleDetail.content'
                                        copyBtnText="复制代码"
                                        :height="1000"
                                />
                            </div>


                        </div>
                    </el-col>


                    <!--                    文章侧栏 信息-->
                    <el-col :span="6">

                        <div class="articleSlider">


                            <!--                            基本信息卡片-->
                            <el-card class="box-card" shadow="hover">

                                <div slot="header">
                                    <span>基本信息</span>
                                </div>

                                <div class="info"> 作者: {{articleDetail.author}}</div>
                                <div class="info"> 原作: {{articleDetail.originalAuthor}}</div>
                                <div class="info"> 点赞:  {{articleDetail.likes}}</div>
                                <div class="info"> 浏览: {{articleDetail.look}}</div>
                                <div class="info"> 创建时间: {{articleDetail.createTime | dateformat}}</div>
                                <div class="info"> 修改时间: {{articleDetail.updateTime | dateformat}}</div>
                                <div class="info"> 点赞状态: <i @click="changeLikeStatus" class="iconfont el-icon-ali-dianzan" :style="isLike == true?'color: red':''"></i></div>
                            </el-card>

                            <!--                            基本信息卡片-->
                            <el-card class="box-card" shadow="hover">

                                <div slot="header">
                                    <div>文章归属</div>
                                </div>

                                <!--                                分类卡片-->
                                <div class="categoryPart">
                                    <h4 style="text-align: center">分类</h4>
                                    <div style="text-align: center">
                                        <el-link type="success" class="category" :underline="false" :href="'/category/' + articleDetail.category.id">{{articleDetail.category.categoryName}}
                                        </el-link>
                                    </div>
                                </div>

                                <el-divider></el-divider>

                                <!--                                标签卡片-->
                                <div class="tagsPart" style="text-align: center">
                                    <h4 style="text-align: center">标签</h4>

                                    <el-tag v-for="(item,index) in articleDetail.tags" :key="item.id" @click="toArticleListByTagsId(item.id)"
                                          :type="tagsStyle[index]">
                                        {{item.tagsName}}
                                    </el-tag>
                                </div>

                            </el-card>

                        </div>


                    </el-col>

                </el-row>
            </div>


        </div>

        <div v-if='articleDetail == null' v-cloak>
            <h1> 找不到本文章</h1>
        </div>
    </div>

</template>

<script>
    import MarkdownPro from 'vue-meditor';
    import https from "../../../https";
    import {Message} from "element-ui";
    import Cookies from 'js-cookie'

    export default {
        name: "articleDetail",
        data() {
            return {
                isLike:false,
                isLook:false,
                isReady: true,
                articleId: this.$route.params.articleId,
                articleDetail: null,
                user: this.$store.getters.getUser,
                tagsStyle: ['', 'success', 'info', 'warning', 'danger']
            }
        },
        mounted: function () {
            this.getArticleDetail()
            this.getLikeStatus()
        },
        methods: {

            // 获取文章详细内容
            getArticleDetail() {

                https.fetchGet('/article/' + this.articleId,).then((res) => {


                    if (res.data.code == 200) {
                        // 更新数据
                        this.articleDetail = res.data.data

                        // 设置已读
                        this.setIsLooks()

                    }
                }).catch((err) => {
                    console.log(err);
                })

            },

            /**
             * 跳转到文章详情页
             * @param articleId
             */
            toArticleListByTagsId(tagsId){
                // console.log(tagsId)
                this.$router.push({
                    path: `/tags/${tagsId}`
                })
            },


            /**
             * 点赞 取消点赞
             */
            changeLikeStatus(){

                if(this.user == null || this.user.id == null){
                    Message({
                        message: '暂未登录, 无法点赞',
                        type: 'error',
                        duration: 5 * 1000
                    })
                    return
                }

                // 拼接链接
                let url = '/userLiked';
                if (this.isLike == false){
                    url = url + '/like';
                }else if(this .isLike == true){
                    url = url + '/unlike';
                }

                // 发送请求
                const userLike = {
                    'likedUserId':this.user.id,
                    'likedArticleId':this.articleId,
                }
                https.fetchPost(url,userLike).then((res) => {


                    if (res.data.code == 200) {

                        // 如果是点赞
                        if (this.isLike == false) {
                            Message({
                                message: '点赞成功,等待系统处理生效! 请勿重新点赞',
                                type: 'success',
                                duration: 3 * 1000
                            })
                            this.setIsLike()
                            this.articleDetail.likes++;
                            // 如果是取消点赞
                        }else if(this.isLike == true){
                            Message({
                                message: '取消点赞成功,等待系统处理生效! 请勿重新点赞',
                                type: 'success',
                                duration: 3 * 1000
                            })
                            this.setIsUnLike()
                            this.articleDetail.likes--;
                        }

                    }
                }).catch((err) => {
                    console.log(err);
                })
            },

            /**
             * 获取点赞状态
             */
            getLikeStatus() {
                // 1. 判断是否用户是否存在
                if (this.user == null || this.user.id == null) {
                    console.log('user:'  +  this.storeUser)
                    return
                }

                // 2. 从cookies中获取
                const cookieKey = this.user.id + ":" + this.articleId
                const isLike = Cookies.get(cookieKey)


                if (isLike != undefined){
                    if (isLike == 'true') {
                        this.isLike = true
                    }else{
                        this.isLike = false
                    }
                }

                // 3. cookies中不存在 向服务器获取
                else if (isLike == undefined) {
                    https.fetchGet('/userLiked/' + this.articleId + '/' + this.user.id).then((res) => {

                        const {data} = res
                        if (data.code == 200) {
                            if (data.data == null) {
                                this.setIsUnLike()
                            }else{
                                this.setIsLike()
                            }
                        }
                    }).catch((err) => {
                        console.log(err);
                    })
                }
            },

            /**
             * 设置文章已读
             * */
            setIsLooks(){
                const cookieKey = this.articleId + ":" + 'look'
                const expires = new Date().getTime() + 10  * 60 *  1000 //10分钟

                // 1. 从 cookies中获取
                const isLook = Cookies.get(cookieKey)
                // 存在 则添加浏览量
                if (isLook !== undefined){
                    return
                }else {
                    // 不存在 则添加流量量
                    https.fetchPut('article/looks/' + this.articleId).then((res) => {

                        const {data} = res
                        if (data.code == 200) {
                            // 设置cookies 10分钟
                            Cookies.set(cookieKey, true, {expires: expires})
                            this.articleDetail.look =  this.articleDetail.look +1
                        }
                    }).catch((err) => {
                        console.log(err);
                    })
                }
            },

            /**
             * 设置喜欢
             */
            setIsLike(){
                this.isLike  = true
                const cookieKey = this.user.id + ":" + this.articleId
                const expires = new Date().getTime() + 10  * 60 *  1000 //10分钟
                Cookies.set(cookieKey,this.isLike,{expires:expires})
            },
            /**
             * 设置不喜欢
             */
            setIsUnLike(){
                this.isLike  = false
                const cookieKey = this.user.id + ":" + this.articleId
                const expires = new Date().getTime() + 10  * 60 *  1000 //10分钟
                Cookies.set(cookieKey,this.isLike,{expires:expires})
            }
        },
        computed:{
            storeUser(){
                return this.$store.state.user;
            }
        },
        watch:{
            storeUser(newVal) {
                this.user = newVal
                this.getLikeStatus()
            },
        },
        components: {
            MarkdownPro
        }

    }
</script>

<style scoped>
    .articleDetail {
        margin: 10px auto;
        width: 100%;
    }

    .title {
        margin: 10px 0 0;
        text-align: center;
        font-weight: 500;
    }

    .articleSlider {
        margin-top: 20px;
    }

    [v-cloak] {
        display: none
    }

    .info {
        font-size: 14px;
        margin: 8px auto;
        font-weight: 600;
    }

    .info:hover {
        color: #409EFF;
    }

    .box-card {
        margin: 20px auto;
    }

    .tagsPart .el-tag {
        margin: 5px 8px
    }

</style>
